package org.javaboy.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.resource.PathResourceResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 这个类的作用就是配置 Spring 容器的，作用类似于 applicationContext.xml
 */
@Configuration
@ComponentScan(basePackages = "org.javaboy.demo", useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)})
@PropertySource("classpath:db.properties")
public class SpringConfig implements EnvironmentAware {

    @Value("${db.username}")
    String username;
    @Value("${db.password}")
    String password;
    @Value("${db.url}")
    String url;

    private Environment env;

    @Bean
    DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername(env.getProperty("db.username"));
        ds.setPassword(env.getProperty("db.password"));
        ds.setUrl(env.getProperty("db.url"));
        return ds;
    }

    @Bean
    SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setTypeAliasesPackage("org.javaboy.demo.model");
//        bean.setMapperLocations(new ClassPathResource("org/javaboy/demo/mapper/UserMapper.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:org/javaboy/demo/mapper/*.xml"));
        return bean;
    }
    @Bean
    MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        configurer.setBasePackage("org.javaboy.demo.mapper");
        return configurer;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }
}
